<?php


class sfGuardUserTable extends PluginsfGuardUserTable
{
    public function getUserIdsWichCanAccessTheSamePortalsThatTheActualUserCan()
    {
        $user = sfContext::getInstance()->getUser()->getGuardUser();

        $q = Doctrine_Query::create()->select('eha.user_id')->from('EmsHasAccess eha');

        $q->andWhere('eha.portal_id IN (SELECT p.portal_id FROM EmsHasAccess p WHERE p.user_id = ?)', $user->getId());
        $q->andWhere('eha.user_id NOT IN (SELECT u.user_id FROM sfGuardUserGroup u INNER JOIN u.Group g WHERE g.name =?)','Administradores');

        $results = array();
        
        foreach ($q->execute() as $key => $result) {
            $results[$key] = $result->getUserId();
        }

        return $results;
    }

    public function addUsersUnderActualUserManagementQuery()
    {
        $q = Doctrine_Query::create()->from('sfGuardUser u');

        $users_ids = $this->getUserIdsWichCanAccessTheSamePortalsThatTheActualUserCan();

        if(empty ($users_ids)){
            $q->whereIn('u.id', array(0)); // array(1,2,3)
        } else {
            $q->whereIn('u.id', $users_ids);
        }

        return $q;
    }
    
    public static function getInstance()
    {
        return Doctrine_Core::getTable('sfGuardUser');
    }
}